<?php

namespace App\Services;

use App\Models\College;
use GuzzleHttp\Client;
use App\Helpers\LoggerHelper;
use Illuminate\Support\Facades\Storage;

class CollegeLogoDownloadService
{
    protected $client;
    protected $logger;

    public function __construct()
    {
        $this->client = new Client([
            'timeout' => 30,
            'verify' => false
        ]);
        $this->logger = LoggerHelper::getLogger('college_logo_download');
    }

    public function downloadAllLogos()
    {
        $colleges = College::select('college_id', 'school_id')
            ->whereNotNull('school_id')
            ->get();

        foreach ($colleges as $college) {
            try {
                $this->downloadLogo($college->school_id, $college->college_id);
                $this->logger->info("Downloaded logo for college_id: {$college->college_id}");
            } catch (\Exception $e) {
                $this->logger->error("Failed to download logo for college_id: {$college->college_id}, Error: " . $e->getMessage());
            }
        }
    }

    private function downloadLogo($schoolId, $collegeId)
    {
        $url = "https://static-data.gaokao.cn/upload/logo/{$schoolId}.jpg";
        $saveDir = dirname(__DIR__, 3) . "\\public\\storage\\images";
        var_dump($saveDir);exit;
        if (!is_dir($saveDir)) {
            mkdir($saveDir, 0777, true);
        }
        $savePath = $saveDir . "\\{$collegeId}.jpg";

        $response = $this->client->get($url, ['sink' => $savePath]);

        if ($response->getStatusCode() !== 200) {
            throw new \Exception("HTTP request failed with status: " . $response->getStatusCode());
        }
    }
}
